/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.ruoyi.api.controller.common;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.ExceptionEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.user.domain.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Controller公共组件
 *
 * @author Mark sunlightcs@gmail.com
 */
public abstract class AbstractApiController {

    /**
     * 获取会员id
     */
    protected Long getUserId() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest servletRequest = attributes.getRequest();
        String accessToken = servletRequest.getHeader(Constants.API_TOKEN);
        if (ObjectUtil.isEmpty(accessToken)) {
            //这里抛给前端的为一个自定义异常枚举，可自己定义
            throw new ServiceException(ExceptionEnum.USER_NOT_LOGIN);
        }
        Object cacheObject = RedisUtils.getCacheObject(Constants.APP_ONLINE_TOKEN_KEY + accessToken);
        User apiUser = BeanUtil.toBean(cacheObject, User.class);

       /* //isThrow 是否抛异常，不抛的话返回常量0
        User user = UserContext.currentUser();
        if (ObjectUtil.isNull(user)){
            throw new ServiceException("用户不存在");
        }*/
        return apiUser.getId();

    }

    /**
     * 获取当前登录老师
     *
     * @return
     */
    protected User getLoginUser() {
        //return UserContext.currentUser();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest servletRequest = attributes.getRequest();
        String accessToken = servletRequest.getHeader(Constants.API_TOKEN);
        if (ObjectUtil.isEmpty(accessToken)) {
            //这里抛给前端的为一个自定义异常枚举，可自己定义
            throw new ServiceException(ExceptionEnum.USER_NOT_LOGIN);
        }
        Object cacheObject = RedisUtils.getCacheObject(Constants.APP_ONLINE_TOKEN_KEY + accessToken);
        return BeanUtil.toBean(cacheObject, User.class);
    }

}
